<template>
  <div>
    <div style="margin-bottom: 20px;">
      <el-card shadow="hover" body-style="width:100%;">
        <div style="display: flex">
          <div style="display: flex;align-items:center;margin-right:20px">
            <i class="el-icon-user" />
          </div>
          <div style="display: flex;align-items:center;margin-right:10px">物料名称：</div>
          <el-input v-model="comment.name" style="width: 200px" placeholder="请输入物料名" clearable />
          <div style="display: flex;align-items:center;margin-left:20px;">
            <i class="el-icon-money" />
          </div>
          <div style="display: flex;align-items:center;margin-left:30px;margin-right:5px ">单位：</div>
          <el-select v-model="comment.unit" placeholder="请选择" clearable>
            <el-option
              v-for="item in optionsTwo"
              :key="item.value"
              :label="item.label"
              :value="item.valueTwo"
            />
          </el-select>
          <div style="display: flex;align-items:center;margin-left:20px;">
            <i class="el-icon-s-promotion" />
          </div>
          <div style="display: flex;align-items:center;margin-left:20px;margin-right:10px">商品种类：</div>
          <!--          <el-input v-model="phone" style="width: 200px" placeholder="请输入频率" clearable />-->
          <el-select v-model="comment.species" placeholder="请选择" clearable>
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <div style="padding: 0px 20px;margin-left: 50px">
            <el-button type="primary" icon="el-icon-search" @click="load">查找</el-button>
          </div>
          <div>
            <el-button type="primary" color="" plain icon="el-icon-info" @click="clearInput">清空</el-button>
          </div>

        </div>
        <div>
          <el-button
            style="background-color: #0d8d84;margin-top: 30px"
            type="info"
            @click="insert"
          >新增</el-button>
        </div>
      </el-card>
    </div>
    <el-card shadow="hover">
      <el-table :data="goodsList" border stripe :header-cell-class-name="'headerBg'" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" sortable>
          <template scope="scope">
            <span>{{ (pageParams.page - 1) * pageParams.pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="商品名称" align="center" />
        <el-table-column prop="shopId" label="所属商家" align="center">
          <template v-slot="{ row }">
            {{ row =1 ?'admin' : '超级管理员' }}
          </template>
        </el-table-column>
        <el-table-column prop="stores" label="库存" align="center" />
        <el-table-column prop="unit" label="单位" align="center" />
        <el-table-column prop="prince" label="价格" align="center">
          <template v-slot="{ row }">
            {{ formatPrice(row.prince) }}
          </template>
        </el-table-column>
        <el-table-column prop="species" label="商品种类" align="center" />
        <el-table-column prop="prop" label="原料图片" width="125px" align="center">
          <template slot-scope="scope">
            <img :src="scope.row.img" width="100px" height="100px">
          </template>
        </el-table-column>
        <!--        <el-table-column prop="shelf" label="是否上架" align="center" />-->
        <el-table-column
          header-align="center"
          align="center"
          prop="shelf"
          label="是否下架"
        >
          <template slot-scope="scope">
            <el-tooltip :content="'是否下架该商品？'" placement="top">
              <el-switch
                v-model="scope.row.shelf"
                active-color="#13ce66"
                inactive-color="#DCDFE6"
                :active-value="'1'"
                :inactive-value="'0'"
                @change="handleChange(scope.row)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="上架时间" width="100px" />
        <el-table-column label="操作" width="300" align="center">
          <template slot-scope="scope">
            <el-button style="margin-right: 20px" type="success" @click="handleEdit(scope.row)">编辑 <i class="el-icon-edit" /></el-button>
            <el-popconfirm
              class="ml-5"
              confirm-button-text="确定"
              cancel-button-text="我再想想"
              icon="el-icon-info"
              icon-color="red"
              title="您确定删除吗？"
              @confirm="deleteById(scope.row)"
            >
              <el-button
                slot="reference"
                style="width: 80px"
                type="danger"
              >删除 <i class="el-icon-remove-outline" /></el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div style="padding: 10px 0">
        <el-pagination
          :current-page="pageParams.page"
          :page-sizes="[2, 5, 10, 20]"
          :page-size="pageParams.pageSize"
          layout="total, sizes, prev, pager, next,jumper"
          :total="pageParams.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <el-dialog title="物料信息" style="margin-left: -15px" :visible.sync="dialogFormVisible" width="40%" :close-on-click-modal="false">
        <div style="background-color: #0d8d84; width: 5px; height:20px; top: -62px;  left: -10px;  position: relative;" />
        <el-form
          ref="ruleForm"
          label-width="140px"
          size="small"
          style="width: 85%;"
          :model="form"
          :rules="rules"
        >
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="form.name" autocomplete="off" />
          </el-form-item>
          <el-form-item label="所属商家" prop="shopId">
            <el-select v-model="form.shopId" placeholder="请选择">
              <el-option
                v-for="item in optionsThree"
                :key="item.value"
                :label="item.label"
                :value="item.valueThree"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="物料库存" prop="stores">
            <el-input v-model="form.stores" autocomplete="off" />
          </el-form-item>
          <el-form-item label="物料价格" prop="prince">
            <el-input v-model="form.prince" autocomplete="off" />
          </el-form-item>
          <el-form-item label="物料单位" prop="unit">
            <el-select v-model="form.unit" placeholder="请选择">
              <el-option
                v-for="item in optionsTwo"
                :key="item.value"
                :label="item.label"
                :value="item.valueTwo"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="物料种类" prop="species">
            <el-select v-model="form.species" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <!-- 上传图片组件-->
          <el-form-item label="物料图片" style="margin-left: 2px" prop="img">
            <el-upload
              class="avatar-uploader"
              action="/dev-api/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="form.img" :src="form.img" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
          <el-form-item label="更新时间" prop="updateTime">
            <el-date-picker v-model="form.updateTime" type="datetime" value-format="timestamp" placeholder="选择日期时间" />
          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Goods',
  data() {
    return {
      // 表单验证
      rules: {
        name: [
          { required: true, message: '请输入物料名字', trigger: 'blur' },
          { min: 1, message: '名字至少一个字', trigger: 'change' }
        ],
        shopId: [
          { required: true, message: '请输入物料所属商家id' },
          {
            pattern:
              /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: '请输入正确的所属商家id',
            trigger: 'blur'
          }
        ],
        unit: [
          { required: true, message: '请选择物料单位', trigger: 'change' }
        ],
        species: [
          { required: true, message: '请选择物料种类', trigger: 'change' }
        ],
        stores: [
          { required: true, message: '请输入物料库存' },
          {
            pattern:
              /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: '请输入正确的库存数量',
            trigger: 'blur'
          }
        ],
        prince: [
          { required: true, message: '请输入物料价格' },
          {
            pattern:
              /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: '请输入正确的价格',
            trigger: 'blur'
          }
        ],
        updateTime: [
          { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
        ],
        img: [{ required: true, message: '请上传菜品图片' }]
      },
      options: [
        { value: '0', label: '面粉' },
        { value: '1', label: '白糖' },
        { value: '2', label: '鸡蛋' },
        { value: '3', label: '牛奶' },
        { value: '4', label: '小苏打' },
        { value: '5', label: '油/黄油' },
        { value: '6', label: '巧克力' },
        { value: '7', label: '水果' }
      ],
      value: '',
      selectedLabel: '',
      optionsTwo: [
        { valueTwo: '0', label: '元' },
        { valueTwo: '1', label: '个' },
        { valueTwo: '2', label: '斤' },
        { valueTwo: '3', label: '罐' }
      ],
      valueTwo: '',
      optionsThree: [
        { valueThree: '1', label: 'admin' }
      ],
      valueThree: '',
      selectedLabelTwo: '',
      tableData: {},
      goodsList: [],
      // 分页参数
      pageParams: {
        page: 1,
        pageSize: 10,
        total: 0
      },
      comment: {
        usersName: '',
        name: '',
        unit: '',
        species: '',
        shopId: 0
      },
      name: '',
      dialogFormVisible: false,
      multipleSelection: [],
      user: localStorage.getItem('user') ? localStorage.getItem('user') : {},
      showSrc: '',
      // 新增|修改获取的表单数据
      form: {
        name: '',
        shopId: 0,
        stores: '',
        prince: 0,
        unit: '',
        species: '',
        img: '',
        updateTime: null
      }
    }
  },
  mounted() {
    this.load()
  },
  methods: {
    async handleChange(row) {
      // 处理状态改变
      console.log(row)
      this.$confirm('此操作将下架该商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const id = {
          id: row.id
        }
        const res = await this.$API.goods.reqshelfById(id)
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '修改成功'
          })
          this.load()
        }
      }).catch(() => {
        this.load()
        this.$message({
          type: 'info',
          message: '已取消下架'
        })
      })
    },
    insert() {
      this.form = {}
      this.dialogFormVisible = true
    },
    cancel() {
      this.$refs.ruleForm.resetFields()
      this.$message({
        type: 'info',
        message: '已取消'
      })
      this.dialogFormVisible = false
    },
    // 上传图片前后函数
    handleAvatarSuccess(res, file) {
      this.form.img = res.data
      this.showSrc = res.data
      console.log('@@@@handleAvatarSuccess-res', res)
      console.log('@@@@handleAvatarSuccess-file', file)
    },
    beforeAvatarUpload(file) {
      // console.log("@@@输出上传之前的file", file);
      // const isJPG = file.type === "image/jpeg";
      // const isLt2M = file.size / 1024 / 1024 < 2;

      // if (!isJPG) {
      //   this.$message.error("上传头像图片只能是 JPG 格式!");
      // }
      // if (!isLt2M) {
      //   this.$message.error("上传头像图片大小不能超过 2MB!");
      // }
      // return isJPG && isLt2M;
    },
    formatPrice(prince) {
      return `${prince} 元 / 斤`
    },
    // 删除这条信息
    async deleteById(row) {
      this.$confirm('删除这条打开信息后后无法回撤, 是否继续?', '删除打卡信息?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const res = await this.$API.goods.reqdeleteById(row)
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.load()
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
          this.load()
        })
    },
    clearInput() {
      this.comment.name = ''
      this.comment.unit = ''
      this.comment.species = ''
      this.load()
    },
    async load() {
      // 种类
      const selectedOption = this.options.find(option => option.value === this.comment.species)
      const selectedLabel = selectedOption ? selectedOption.label : ''

      // 单位
      const selectedOption1 = this.optionsTwo.find(option => option.valueTwo === this.comment.unit)
      const selectedLabel1 = selectedOption1 ? selectedOption1.label : ''
      console.log(selectedLabel)
      console.log(selectedLabel1)

      this.comment.unit = selectedLabel1
      this.comment.species = selectedLabel
      this.comment.usersName = this.user
      const res = await this.$API.goods.reqmessageByPage(this.pageParams, this.comment)
      if (res.code === 200) {
        this.pageParams.total = res.data.total
        this.goodsList = res.data.goodsVoList
      }
    },
    // 新增，更新
    async save() {
      this.$refs.ruleForm.validate(async(valid) => {
        if (valid) {
          // 种类
          const selectedOption = this.options.find(option => option.value === this.form.species)
          const selectedLabel = selectedOption ? selectedOption.label : this.form.species
          // 商家
          const selectedOption2 = this.optionsThree.find(option => option.valueThree === this.form.shopId)
          const selectedLabel12 = selectedOption2 ? selectedOption2.label : this.form.shopId
          // 单位
          const selectedOption1 = this.optionsTwo.find(option => option.valueTwo === this.form.unit)
          const selectedLabel1 = selectedOption1 ? selectedOption1.label : this.form.unit
          console.log(selectedLabel)
          console.log(selectedLabel1)
          this.comment.unit = selectedLabel1
          this.comment.species = selectedLabel

          this.tableData.unit = selectedLabel1
          this.tableData.species = selectedLabel
          this.tableData.name = this.form.name
          this.tableData.shopId = selectedLabel12
          this.tableData.stores = this.form.stores
          this.tableData.prince = this.form.prince
          this.tableData.img = this.form.img
          this.tableData.createTime = this.form.createTime
          console.log(this.form.createTime)
          const res = await this.$API.goods.reqInsertOrUpdate({ ...this.tableData })
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '保存成功'
            })
            this.dialogFormVisible = false
            this.load()
          }
        } else {
          this.$message({
            type: 'error',
            message: '请输入必填项!!!'
          })
          return false
        }
      })
    },
    handleEdit(row) {
      this.form = JSON.parse(JSON.stringify(row))
      console.log(this.form)
      this.tableData = row
      this.dialogFormVisible = true
    },
    handleSelectionChange(val) {
      console.log(val)
      this.multipleSelection = val
    },

    handleSizeChange(pageSize) {
      console.log(pageSize)
      this.pageParams.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      console.log(pageNum)
      this.pageParams.page = pageNum
      this.load()
    }
  }

}
</script>

<style>
.headerBg {
  background: #eee!important;
}.avatar-uploader .el-upload {
   border: 1px dashed #d9d9d9;
   border-radius: 6px;
   cursor: pointer;
   position: relative;
   overflow: hidden;
 }
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

